package com.chenyu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.chenyu.client.AuthClients;
import com.chenyu.domain.LoginUser;
import com.chenyu.domain.User;
import com.chenyu.mapper.UserMapper;
import com.chenyu.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.chenyu.util.AjaxResult;
import com.chenyu.util.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author chenyu
 * @since 2024-07-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthClients  authClients;


    public AjaxResult register(Map<String, String> params) {
        String mobile = params.get("mobile"); //手机号
        String imageCode = params.get("imageCode"); //图形验证码
        String smsCode = params.get("smsCode");  //手机验证码
        String password = params.get("password");  //密码
        String regChannel = params.get("regChannel");

        //String regChannel = params.get("regChannel");
        //1.前端传入参数的非空判断
        if (
                StringUtils.isBlank(mobile)
                        || StringUtils.isBlank(imageCode)
                        || StringUtils.isBlank(password)
                        || StringUtils.isBlank(smsCode)
        ){
            return AjaxResult.error("输入参数有误，请检查后重试！");
        }
        //此时已经通过图形验证码获取到了手机验证码，因此不需要在对图形验证码进行验证

        //2. 判断手机号是否已经注册
        EntityWrapper<User> wrapper = new EntityWrapper();
        wrapper.eq("phone", mobile);
        User dbUser = selectOne(wrapper);
        if (dbUser != null){
            return AjaxResult.error("该账号已注册！");
        }
        //3.对redis中的手机验证码进行校验
        Map<String,Object> mobileMap = (Map<String,Object>)redisTemplate.opsForHash().entries("reg:" + mobile);
        if (mobileMap == null || mobileMap.size() == 0){
            //redis中的手机验证码已经过期
            return AjaxResult.error("手机验证码已过期！");
        }
        Object redisCode = mobileMap.get("code");
        if ( !StringUtils.equals(smsCode,redisCode.toString()) ){
            return AjaxResult.error("手机验证码错误！");
        }

        //4. 参数已全部校验完成，将数据添加到数据库中
        //   创建user对象添加到数据库，并对t_logininfo进行数据同步
        //4.1  创建User对象
        User  user = createUser(mobile,password);
        //调用 重写的insertOne方法（注意：user中又logininfo的外键 需要先插入loginUser得到主键值后  再赋值给user  最后插入user
        insertOne(user);
        return new AjaxResult();
    }

    public User createUser(String mobile, String password) {
        User user = new User();
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        user.setPhone(mobile);
        //设置加密的盐
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //对密码进行md5加密
        String md5Pwd = DigestUtils.md5DigestAsHex( (password + salt).getBytes() );
        user.setPassword(md5Pwd);
        return user;
    }

    public void insertOne(User user) {
        //user中又loginUser的外键 需要先插入loginUser得到主键值
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(user.getPhone());
        loginUser.setPassword(user.getPassword());
        loginUser.setTel(user.getPhone());
        loginUser.setType(1);
        AjaxResult result = authClients.addOrUpdate(loginUser);
        //loginUser得到主键值后  再赋值给user  最后插入user
        user.setLoginId( Long.parseLong(result.getData().toString() ) );
        insert(user);
    }
}
